package com.hundsun.yr.universal.library.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.hundsun.yr.universal.library.R;

import java.util.Map;


/**
 * @Title: BrowserLayout.java 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @date 2015-10-22 下午4:12:10 
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com 
 * @replace author:
 * @replace date:
 * @version V1.0   
 */
public class BrowserLayout extends LinearLayout {

    private Context mContext = null;
    public WebView mWebView = null;
    private View mBrowserControllerView = null;
    private ImageButton mGoBackBtn = null;
    private ImageButton mGoForwardBtn = null;
    private ImageButton mGoBrowserBtn = null;
    private ImageButton mRefreshBtn = null;

    private int mBarHeight = 5;
    private ProgressBar mProgressBar = null;

    private String mLoadUrl;
    private Map mHeader;

        public BrowserLayout(Context context) {
            super(context);
            init(context);
    }

    public BrowserLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    @SuppressWarnings("deprecation")
	@SuppressLint({ "InflateParams", "SetJavaScriptEnabled" }) 
    private void init(Context context) {
        mContext = context;
        setOrientation(VERTICAL);

        mProgressBar = (ProgressBar) LayoutInflater.from(context).inflate(R.layout.progress_horizontal, null);
        mProgressBar.setMax(100);
        mProgressBar.setProgress(0);
        addView(mProgressBar, LayoutParams.MATCH_PARENT, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mBarHeight, getResources().getDisplayMetrics()));

        mWebView = new WebView(context);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        //设置 缓存模式
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); 
//        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        //提高渲染的优先级
        mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
        mWebView.getSettings().setBuiltInZoomControls(false);
        mWebView.getSettings().setSupportMultipleWindows(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setAllowFileAccess(false);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        // 开启 DOM storage API 功能 
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setLoadsImagesAutomatically(true);
        mWebView.getSettings().setSavePassword(false);
		mWebView.getSettings().setDatabaseEnabled(true);
//      mWebView.getSettings().setBlockNetworkImage(true);

		if(Build.VERSION.SDK_INT >= 21) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
		} else {
//			mWebView.getSettings().setLoadsImagesAutomatically(false);
		}
		mWebView.setLayerType(View.LAYER_TYPE_HARDWARE,null);
		this.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        LayoutParams lps = new LayoutParams(LayoutParams.MATCH_PARENT, 0, 1);
        addView(mWebView, lps);

        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    mProgressBar.setVisibility(View.GONE);
                } else {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
            }
        });

        mWebView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mLoadUrl = url;

                if(!mWebView.getSettings().getLoadsImagesAutomatically()) {
                	mWebView.getSettings().setLoadsImagesAutomatically(true);
                }
            }
            
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            	// TODO Auto-generated method stub
            	//handler.cancel(); // Android默认的处理方式
            	//handleMessage(Message msg); // 进行其他处理
            	 handler.proceed();  // 接受所有网站的证书
                handler.cancel();
//            	 super.onReceivedSslError(view, handler, error);
            }

        });

        mBrowserControllerView = LayoutInflater.from(context).inflate(R.layout.browser_view_controller, null);
        mBrowserControllerView.setVisibility(GONE);
        mGoBackBtn = (ImageButton) mBrowserControllerView.findViewById(R.id.browser_controller_back);
        mGoForwardBtn = (ImageButton) mBrowserControllerView.findViewById(R.id.browser_controller_forward);
        mGoBrowserBtn = (ImageButton) mBrowserControllerView.findViewById(R.id.browser_controller_go);
        mRefreshBtn = (ImageButton) mBrowserControllerView.findViewById(R.id.browser_controller_refresh);

        mGoBackBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (canGoBack()) {
                    goBack();
                }else{
                	((Activity) mContext).finish();
                }
            }
        });

        mGoForwardBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (canGoForward()) {
                    goForward();
                }
            }
        });

        mRefreshBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                loadUrl(mLoadUrl);
            }
        });

        mGoBrowserBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            	goBrowser();
            }
        });

        mWebView.setDownloadListener(new BrowserDownload());

        addView(mBrowserControllerView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }

    
    /**
     * 加载网页Url或者本地Url
     * @param url
     */
    public void loadUrl(String url) {
    	mWebView.loadUrl(url);
    }

    /**
     * 加载网页url+header
     * @param url
     * @param header
     */
    public void loadUrl (String url, Map header){
        mWebView.loadUrl(url,header);
    }

    /**
     * 加载网页数据（data）
     */
    public void loadData(String html) {
    	mWebView.loadData(html, "text/html; charset=UTF-8", "null");
    }
    
    
    /**
     * 加载包含图片的网页数据（data）
     */
    public void loadDataWithBaseURL(String html) {
    	
    	mWebView.loadDataWithBaseURL("about:blank", html, "text/html", "utf-8", null);
    }
    
    /**
     * 是否可以后退
     * @return
     */
    public boolean canGoBack() {
        return null != mWebView ? mWebView.canGoBack() : false;
    }

    /**
     * 是否可以前进
     * @return
     */
    public boolean canGoForward() {
        return null != mWebView ? mWebView.canGoForward() : false;
    }
    
    
    /**
     * 跳转到浏览器
     */
    public void goBrowser(){
    	if (!TextUtils.isEmpty(mLoadUrl)) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(mLoadUrl));
            mContext.startActivity(intent);
        }
    }
    
    /**
     * 刷新
     */
    public void refresh(){
    	if (null != mWebView) {
            if (mHeader != null && !mHeader.isEmpty()){
                loadUrl(mLoadUrl,mHeader);
            }else{
                loadUrl(mLoadUrl);
            }
    	}
    }

    /**
     * 返回
     */
    public void goBack() {
        if (null != mWebView) {
            mWebView.goBack();
        }
    }

    /**
     * 前进
     */
    public void goForward() {
        if (null != mWebView) {
            mWebView.goForward();
        }
    }

    public WebView getWebView() {
        return mWebView != null ? mWebView : null;
    }

    public void hideBrowserController() {
        mBrowserControllerView.setVisibility(View.GONE);
    }

    public void showBrowserController() {
        mBrowserControllerView.setVisibility(View.VISIBLE);
    }
    
    class BrowserDownload implements DownloadListener{  
    	  
    	@Override  
    	public void onDownloadStart(String url, String userAgent,  
    			String contentDisposition, String mimetype, long contentLength) {  
    		/**
    		 * 调用自己的下载方式  
    		 * 
    		 * (尚未实现)
    		 * 
    		 * 调用自己的下载方式  
    		 */
    		//调用系统浏览器下载  
    		Uri uri = Uri.parse(url);    
    		Intent intent = new Intent(Intent.ACTION_VIEW, uri);    
    		mContext.startActivity(intent);        
    	}  
          
    }

}
